import { app } from "../../../base/typings/global";
import { Handler } from "../../../base/utils/Handler";
import { EmptyAnalyticsSender } from "../IAnalyticsAble";


/**
 * 内部阿里云日志事件上报器
 */
export class HLAnalyticsSender extends EmptyAnalyticsSender {
    protected _api:string = "https://api.game.hnquyou.com/api/game-event/v2/report/send";
    protected _eventCache:any[] = [];

    constructor(reportError?:boolean, exclude?:string[]) {
        super(reportError, exclude);
        app.timer.loop(2000, this, this._doReport);
    }

    protected _doReport():void {
        if(this._eventCache.length <= 0) {
            return;
        }
        let count:number = Math.min(this._eventCache.length, 5);
        app.net.http.post(this._api, {
            data: this._eventCache.splice(0, count),
            responseType: "json",
            retryTimes: 3,
            onComplete:Handler.create(this, (e)=>{
                if (e && e.status && Number(e.status) != 200) {
                    console.error(`HL事件统计上报失败:${JSON.stringify(e)}`)
                }
            }),
            onError:Handler.create(this, (e)=>{
                console.error(`HL事件统计上报接口异常:${JSON.stringify(e)}`)
            })
        })
    }

    
    async send(eventName: string, data: any): Promise<void> {
        data['_event'] = eventName;
        let msg_data = {
            "appid": app.publisher.appId,
            "openid": app.storage.userId || app.publisher.login.openID,
            "level":"info",
            "data":data
        }
        this._eventCache.push(msg_data);
    }
}
